package com.cn.esermis.config.sharding;

import cn.hutool.core.date.DateUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.shardingsphere.api.sharding.standard.RangeShardingAlgorithm;
import org.apache.shardingsphere.api.sharding.standard.RangeShardingValue;

import java.util.*;

/**
 * 4.1version 范围分片 -- 范围查询使用
 */
@Slf4j
public class MonthRangeShardingAlgorithm implements RangeShardingAlgorithm<Date> {

    @Override
    public Collection<String> doSharding(Collection<String> collection, RangeShardingValue<Date> rangeShardingValue) {
        log.info("collection:{},rangeShardingValue:{}", collection, rangeShardingValue);
        Set<String> set = new HashSet<>();
        Date lowerEndpoint = rangeShardingValue.getValueRange().lowerEndpoint();
        Date upperEndpoint = rangeShardingValue.getValueRange().upperEndpoint();
        Integer start = Integer.parseInt(DateUtil.format(lowerEndpoint, "yyyyMM"));
        Integer end = Integer.parseInt(DateUtil.format(upperEndpoint, "yyyyMM"));
        for(String item:collection){
            String[] split = item.split("_");
            if(Integer.parseInt(split[split.length-1]) >= start && Integer.parseInt(split[split.length-1]) <= end){
                set.add(item);
            }
        }
        log.info("range真实路由的表:{}", set);
        return set;
    }
}

